﻿using FastCode.DTO;
using FastCode.Models;
using Microsoft.AspNetCore.Mvc;

namespace FastCode.Services
{
    public class DBConfigService : BaseService
    {
        protected ISqlSugarClient db;

        public DBConfigService(ISqlSugarClient _db)
        {
            db = _db;
        }


        /// <summary>
        ///     
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<List<DbColumnInfo>> GetDbColumnInfoAsync(DBConfigDTO dto)
        {
            ISqlSugarClient? configDb;
            if (dto.Id == 0)
            {
                configDb = db;
            }
            else
            {
                configDb = await GetSqlClientAsync(dto.Id);
            }

            var columnInfos = configDb.DbMaintenance.GetColumnInfosByTableName(dto.TableName, false);

            return columnInfos;
        }

        /// <summary>
        /// 获取数据库客户端
        /// </summary>
        /// <param name="dbConfigId"></param>
        /// <returns></returns>
        public async Task<SqlSugarClient> GetSqlClientAsync(int dbConfigId)
        {
            var item = await db.Queryable<DBConfig>().FirstAsync(x => x.Id == dbConfigId);
            var testDb = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = item.ConnectStr,
                DbType = item.EDBType,
                IsAutoCloseConnection = true
            });

            return testDb;
        }
    }
}
